//
//  CIImage+Ext.swift
//  TTCOM
//
//  Created by Toj on 6/9/22.
//

import Foundation
import CoreImage
import UIKit

public extension CIImage {
    
    /**
     * 条码移除模糊效果(推荐, 经测试比位图快很多)
     * 此方法不唯一, 也可以用位图上下文方式
     */
    func removeEffect(size: CGSize) -> UIImage? {
        // extent 图片的frame
        let scaleX = size.width / extent.size.width
        let scaleY = size.height / extent.size.height
        let transform = CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY)
        let resultImage = transformed(by: transform)
        let image = UIImage(ciImage: resultImage)
        return image
    }
    
    func reoutputImage(size: CGSize) -> UIImage? {
        
        // extent 图片的frame
        let swidth = extent.size.width
        let sheight = extent.size.height
        
        let wscale = size.width / swidth
        let hscale = size.height / sheight
        
        let width = Int(swidth * wscale)
        let height = Int(sheight * hscale)
        
        let colorSpaceRef = CGColorSpaceCreateDeviceGray()
        let bitmapInfo = cgImage?.bitmapInfo.rawValue ?? 0
        
        let contextRef = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpaceRef, bitmapInfo: bitmapInfo)
        contextRef?.interpolationQuality = .none
        contextRef?.scaleBy(x: wscale, y: hscale)
        
        let context = CIContext(options: nil)
        guard let imageRef = context.createCGImage(self, from: extent) else { return nil }
        contextRef?.draw(imageRef, in: extent)
        
        guard let cgImage = contextRef?.makeImage() else { return nil }
        
        return UIImage(cgImage: cgImage)
    }
}
